package com.xinz.config;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class GlobalConfig {
	
	private static Element root = null;
	private static Element global = null;
	private static Element res = null;
	
	// Server
	private static Map<Integer, Element> serverMap = new HashMap<Integer, Element>();
	// Memcached
	private static Map<String, Element> memcachedMap = new HashMap<String, Element>();
	
	private static Document document = null;

	/**
	 * 初始化
	 * @param file
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static void init(String file) throws Exception {
		SAXReader reader = new SAXReader();
		document = reader.read(GlobalConfig.class.getClassLoader().getResourceAsStream("config.xml"));
		root = document.getRootElement();
		if(root == null) {
			throw new Exception("no root node in config");
		}
		// 全局变量
		global = root.element("global");
		if(global == null) {
			throw new Exception("no global node in config");
		}
		// 配置库
		res = global.element("res");
		if(res == null) {
			throw new Exception("no res node in config");
		}
		
		// Server
		List<Element> servers = root.elements("server");
		for(Iterator<Element> it = servers.iterator(); it.hasNext();) {
			Element e = it.next();
			serverMap.put(Integer.parseInt(e.attributeValue("id")), e);
		}
		
		// Memcached
		Element memcached = root.element("Memcached");
		if(memcached == null) {
			throw new Exception("no Memcached node in config");
		}
		List<Element> pools = memcached.elements("pool");
		for(Iterator<Element> it = pools.iterator(); it.hasNext();) {
			Element e = it.next();
			memcachedMap.put(e.attributeValue("name"), e);
		}
	}
	
	/**
	 * 获取配置库
	 * @return
	 */
	public static Element getRes() {
		return res;
	}
	
	/**
	 * 获取Server信息
	 * @param serverId
	 * @return
	 */
	public static Element getServer(int serverId) {
		Element serverElement = serverMap.get(serverId);
		return serverElement;
	}
	
	/**
	 * 根据名称来获取memcached配置
	 * @param poolName
	 * @return
	 */
	public static Element getMemcached(String poolName) {
		return memcachedMap.get(poolName);
	}
}
